package cn.zhiquxing;

import cn.zhiquxing.test.Good;
import cn.zhiquxing.test.IGood;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;

public class CommunicatPetStore {
    public static final int max_amount = 10; // 数据缓冲区
    
    static class DataBuffer<T> {
        private List<T> dataList = new LinkedList<T>();
        //数据缓冲区长度
        private Integer amount = 0;
        
        private final Object lock_object = new Object();
        private final Object not_full = new Object();
        private final Object not_empty = new Object();
        
        public void add(T element) throws InterruptedException {
            while (amount > max_amount) {
                synchronized (not_full) {
                    System.out.println("队列已将满了");
                    not_full.wait();
                }
                synchronized (lock_object) {
                    dataList.add(element);
                    amount++;
                }
                synchronized (not_empty) {
                    not_empty.notify();
                }
            }
        }
        
        public T fetch() throws Exception {
            while (amount <= 0) {
                synchronized (not_empty) {
                    System.out.println("队列已经空了");
                    not_empty.wait();
                }
            }
            T element = null;
            synchronized (lock_object) {
                element = dataList.remove(0);
                amount--;
            }
            synchronized (not_full) {
                not_full.notify();
            }
            return element;
        }
    }


    public static void main(String[] args) {
        System.out.println("当前线程id" + Thread.currentThread().getId());
        System.setErr(System.out);
        DataBuffer<IGood> dataBuffer = new DataBuffer();//
        Callable<IGood> productAction = () -> {
            IGood good = new Good();
            dataBuffer.add(good);
            return good;
        };
    }
}
